﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Common.Extensions
{
    public static class AddAuthenticationExtension
    {
        public static void AddAuthenticationExt(this WebApplicationBuilder builder)
        {
            // 配置认证服务
            builder.Services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                var audienceConfig = builder.Configuration["Audience:Audience"];
                var symmetricSecurityKey = builder.Configuration["Audience:Secret"];
                var iss = builder.Configuration["Audience:Issuer"];
                var keyByteArray = Encoding.ASCII.GetBytes(symmetricSecurityKey);
                var singleKey = new SymmetricSecurityKey(keyByteArray);

                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = singleKey,
                    ValidateIssuer = true,
                    ValidIssuer = iss,
                    ValidateAudience = true,
                    ValidAudience = audienceConfig, // 订阅人
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    RequireExpirationTime = true
                };
                // 如果是通过 Url 或者 cookie 来传递 Token，可以使用如下方式接受
                o.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        context.Token = context.Request.Query["access_token"];
                        return Task.CompletedTask;
                    }
                };
            });
        }


    }
}
